package com.hs.telepass.controller.task;


import android.content.Intent;
import com.hs.telepass.controller.TaskController;
import com.hs.telepass.model.json.response.StartResponseItemJson;
import com.hs.telepass.model.json.response.StartSingouSessionResponseJson;
import com.hs.telepass.utils.JsonUtil;
import com.hs.telepass.utils.security.AESEnc;
import com.hs.telepass.utils.security.Base64Utils;

public class StartSingouSessionTask extends Task{
    public final static String ACTION_START_SINGOU_SESSION_TASK = "action_start_singou_session_task";
    public final static String ACTION_START_FOR_PASSWORD_TASK = "action_start_for_password_task";

    private String jsonRequstStr;
    private String taskUrl;
    private int requestType;
    private String runtimeKey;
    private boolean isFromUpdatePassword;

    public StartSingouSessionTask(String runtime_key, String requstJson, boolean isFromUpdatePassword){
        jsonRequstStr = "req=" + requstJson;
        requestType = TASK_REQUST_TYPE_POST;
        this.runtimeKey = runtime_key;
        taskUrl = BASE_API_URL + "/app/" + "start";
        this.isFromUpdatePassword = isFromUpdatePassword;
    }

    @Override
    public void onExecuted(String response, int httpCode) {
        Intent intent = new Intent(getActionName());
        StartSingouSessionResponseJson responseJson = JsonUtil.fromJson(response, StartSingouSessionResponseJson.class);
        String code = responseJson.getCode();
        if("200".equals(code)){
            intent.putExtra(TaskController.EXTRA_EVENT, TaskController.EVENT_TASK_SUCCEED);
            String encRespItem = responseJson.getResp();

            AESEnc aesEnc = new AESEnc(runtimeKey.getBytes());
            StartResponseItemJson itemJson;
            try {
                String decEnc = new String(aesEnc.decrypt(Base64Utils.decode(encRespItem)));
                itemJson = JsonUtil.fromJson(decEnc, StartResponseItemJson.class);

                intent.putExtra(TaskController.EXTRA_RESPONSE, itemJson);
            } catch (Exception e) {
                e.printStackTrace();
                intent.putExtra(TaskController.EXTRA_EVENT, TaskController.EVENT_TASK_ERROR);
            }
        }else{
            intent.putExtra(TaskController.EXTRA_EVENT, TaskController.EVENT_TASK_ERROR);
        }
        broadcastManager.sendBroadcast(intent);
    }

    @Override
    public int getRequstType() {
        return requestType;
    }

    @Override
    public String getJsonRequstStr() {
        return jsonRequstStr;
    }

    @Override
    public int getResponseSuccessCode() {
        return 0;
    }

    @Override
    public String getTaskUrl() {
        return taskUrl;
    }

    @Override
    public String getActionName() {
        if(isFromUpdatePassword)
            return ACTION_START_FOR_PASSWORD_TASK;
        else
            return ACTION_START_SINGOU_SESSION_TASK;
    }
}
